﻿#include "chatroom.h"
#include "ui_chatroom.h"
#include <QBuffer>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMenu>
#include <QPlainTextEdit>
#include <QSettings>
#include <librtc.h>
#include "chatlistviewer.h"
#include "clientcallback.h"
#include "confsettings.h"
#include "contactuser.h"
#include "globaltools.h"
#include "httppost.h"
#include "litedb.h"
#include "mainwidget.h"
#include "mediadevicedialog.h"
#include "notifylabel.h"
#include "protohash.h"
#include "repository.h"
#include "servertimesync.h"
#include "videolayoutconfig.h"
#include "videoeffect.h"
#include "uitools.h"
#include "usersettings.h"

static const int width = 24;
static const int height = 24;

ChatRoom::ChatRoom(const BaseChannelInfo &channel_info, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ChatRoom), uniqueId(channel_info.uniqueId()), myid(ClientCallback::instance()->get_my_id()), microphone_mute_inited(false), self_speaking(false), acting_button(Q_NULLPTR), volumeShowing(0), volumeCalculated(0), notifyLabel(Q_NULLPTR)
{
    ui->setupUi(this);
    setWindowTitle(channel_info.display());

#ifdef Q_OS_WIN
    auto effect = VideoEffect::instance();
    ui->button_screen->setChecked(effect->effFlag == VideoEffect::ScreenEffect);
    ui->button_window->setChecked(effect->effFlag == VideoEffect::WindowEffect);
#else
    ui->button_window->hide();
#ifdef Q_OS_MACOS
    ui->button_screen->hide();
    ui->button_pip->hide();
#else
    auto effect = VideoEffect::instance();
    ui->button_screen->setChecked(effect->effFlag == VideoEffect::ScreenEffect);
#endif
#endif
    //ui->videoLayout->resetGrid(1, 1);

    auto settings = UserSettings::instance();
    settings->setValue(UserSettings::sys_micphone_mute, false);
    settings->setValue(UserSettings::sys_speaker_mute, false);

    refreshUserListViews(channel_info.member_list);
}

ChatRoom::~ChatRoom()
{
    VideoEffect::instance()->endEffect();
    delete ui;
}

qint64 ChatRoom::getUniqueId() const
{
    return uniqueId;
}

qint64 ChatRoom::getId() const
{
    return BaseChannelInfo::idFromUniqueId(uniqueId);
}

qint64 ChatRoom::getRid() const
{
    return BaseChannelInfo::isP2PFromUniqueId(uniqueId) ?
                P2PChanneInfo::p2pchannel_room_id : BaseChannelInfo::idFromUniqueId(uniqueId);
}

void ChatRoom::initWith(MainWidget *main)
{
    connect(this, SIGNAL(deleteChannelMessage(qint64)), main, SLOT(deleteChannelMessage(qint64)));
    auto textviewer = ui->chatWidget->getTextShow();
    textviewer->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(textviewer, &ChatListViewer::cleared, this, &ChatRoom::slot_textShow_cleared);
}

bool ChatRoom::hasFunction(int functionId)
{
    return function_list.contains(functionId);
}

void ChatRoom::clearMessage()
{
    ui->chatWidget->getTextShow()->clearAll();
}

bool ChatRoom::handle_video_contentMenu(QMenu *menu, int micid, qint64 uid)
{
    Q_UNUSED(menu)
    Q_UNUSED(micid)
    Q_UNUSED(uid)
    return false;
}

void ChatRoom::handle_share_command()
{
    QString text = QObject::trECSUTF8("收到自动分享视频指令，");
    //如果没有申请，则自动申请
    if(!ui->button_camera->isEnabled())
        text.append(QObject::trECSUTF8("但目前是不可分享状态"));
    else if(!ui->button_camera->isChecked())
    {
        ui->button_camera->click();
        text.append(QObject::trECSUTF8("已自动申请分享"));
    }
    else
        text.append(QObject::trECSUTF8("但目前已在分享状态"));
    ui->chatWidget->getTextShow()->append(text);
    QApplication::alert(this);
}

void ChatRoom::handle_mic_state(const QList<QVariantHash> &mics, const QList<QVariantHash> &applies, bool isInit)
{
    auto itemsToCheck = userListItems;
    QVector<QVariantHash> mic_list(mics.size());
    QMap<int, qint64> new_video_mic;
    for (int i = 0; i < mics.size(); i++)
    {
        auto &mic = mic_list[i] = mics[i];
        int mic_id = getParam(mic, cmd_param_mic_id).toInt();
        qint64 user_id = getParam(mic, cmd_param_uid).toLongLong();
        int video_id = getParam(mic, cmd_param_video_id).toInt();
        if(user_id > 0 && mic_id > 0 && video_id > 0)
            new_video_mic[mic_id] = user_id;
        if(user_id == 0)
            continue;
        auto find = itemsToCheck.find(user_id);
        if(find == itemsToCheck.end())
            continue;
        auto listItem = find.value();
        itemsToCheck.erase(find);
        if(!listItem)
            continue;
        bool changed = false;
        if(listItem->data(MIC_ROLE).toInt() != mic_id)
        {
            changed = true;
            listItem->setData(MIC_ROLE, mic_id);
        }
        bool hasVideo = getParam(mic, cmd_param_video_id).toInt() > 0;
        if(listItem->data(VIDEO_ROLE).toBool() != hasVideo)
        {
            changed = true;
            listItem->setData(VIDEO_ROLE, hasVideo);
        }
        if(changed)
        {
            QString text = listItem->data(NAME_ROLE).toString();
            text.append('(');
            if(getParam(mic, cmd_param_video_id).toInt() > 0)
                text.append(QObject::trECSUTF8("视频"));
            else
                text.append(QObject::trECSUTF8("对讲"));
            text.append(')');
            listItem->setText(text);
        }
        if(!listItem->flags().testFlag(Qt::ItemIsDragEnabled))
            listItem->setFlags(listItem->flags() | Qt::ItemIsDragEnabled);
    }

    QVector<qint64> apply_list;
    apply_list.resize(applies.size());
    for (int i = 0; i < applies.size(); i++)
    {
        qint64 user_id = apply_list[i] = getParam(applies[i], cmd_param_uid).toLongLong();
        if(user_id == 0)
            continue;
        auto find = itemsToCheck.find(user_id);
        if(find == itemsToCheck.end())
            continue;
        auto listItem = find.value();
        itemsToCheck.erase(find);
        if(!listItem)
            continue;
        int apply_index = - (i + 1);
        if(listItem->data(MIC_ROLE).toInt() != apply_index)
        {
            listItem->setData(MIC_ROLE, apply_index);
            QString text = listItem->data(NAME_ROLE).toString();
            text.append('(').append(QObject::trECSUTF8("等待")).append(')');
            listItem->setText(text);
        }
        if(listItem->flags().testFlag(Qt::ItemIsDragEnabled))
            listItem->setFlags(listItem->flags() & ~Qt::ItemIsSelectable);
    }

    if(isInit || mic_list_ != mic_list)
        ui->videoPage->handle_mic_state(new_video_mic, userListItems);
    else if(apply_list_ == apply_list)
        return;

    for(auto it = itemsToCheck.constBegin(); it != itemsToCheck.constEnd(); it++)
    {
        auto listItem = it.value();
        if(!listItem)
            continue;
        if(listItem->data(MIC_ROLE).toInt() != 0)
        {
            listItem->setData(MIC_ROLE, 0);
            if(listItem->data(VIDEO_ROLE).toBool())
                listItem->setData(VIDEO_ROLE, false);
            listItem->setText(listItem->data(NAME_ROLE).toString());
        }
    }

    mic_list_.swap(mic_list);
    if(apply_list_.size() > 0 || apply_list.size() > 0)
        apply_list_.swap(apply_list);
}

void ChatRoom::handle_text_msg(int type, const QVariantHash &msg)
{
    auto mid = getParam(msg, cmd_param_mid).toByteArray();
    if(!mid.isEmpty() && ui->chatWidget->getTextShow()->hasMid(mid))
        return;
    auto src_id = getParam(msg, cmd_param_snd_id).toLongLong();
    auto timestamp = getParam(msg, cmd_param_msg_time).toLongLong();
    auto snd_name = getParam(msg, cmd_param_snd_name).toString();
    if(snd_name.isEmpty())
        snd_name = getName(src_id);
    int insertedRow = -1;
    if(type == msg_type_text)
    {
        insertedRow = ui->chatWidget->getTextShow()->showChat(src_id == myid, getDecoration(src_id), snd_name, getParam(msg, cmd_param_msg).toString(), timestamp);
    }
    else if(type == msg_type_image)
    {
        auto json = QJsonDocument::fromJson(getParam(msg, cmd_param_msg).toByteArray());
        QString src = json.object()["i"].toString();
        if(!src.isEmpty())
            insertedRow = ui->chatWidget->getTextShow()->showImage(src_id == myid, getDecoration(src_id), snd_name, src.toHtmlEscaped(), timestamp);
    }
    else if(type == msg_type_audio)
    {
        insertedRow = ui->chatWidget->getTextShow()->showChat(src_id == myid, getDecoration(src_id), snd_name, QObject::trECSUTF8("[语音](目前电脑端不支持播放)"), timestamp);
    }
    else if(type == msg_type_video)
    {
        insertedRow = ui->chatWidget->getTextShow()->showChat(src_id == myid, getDecoration(src_id), snd_name, QObject::trECSUTF8("[视频](目前电脑端不支持播放)"), timestamp);
    }
    if(insertedRow >= 0)
    {
        QString text;
        if(BaseChannelInfo::isP2PFromUniqueId(uniqueId) && BaseChannelInfo::idFromUniqueId(uniqueId) != src_id)
        {
            int state = getParam(msg, cmd_param_state).toInt();
            if(state == msg_state_peer_read)
                text = QObject::trECSUTF8("已读");
            else if(state == msg_state_send_fail)
                text = QObject::trECSUTF8("发送失败");
            else
                text = QObject::trECSUTF8("未读");
        }
        ui->chatWidget->getTextShow()->initMid(mid, insertedRow, text);
    }
}

void ChatRoom::handle_msg_list(const QList<QVariantHash> &msgList)
{
    for(const auto &msg : msgList)
    {
        handle_msg(getParam(msg, cmd_param_msg_type).toInt(), msg);
    }
}

void ChatRoom::handle_notify(qint64 src_id, const string &text, const string &name)
{
    Q_UNUSED(name)
    if(text == "STARTSPEAK" || text == "STARTVOIP")
        startNotifySpeak(src_id, true);
    else if(text == "STOPSPEAK" || text == "STOPVOIP")
        stopNotifySpeak(src_id);
}

void ChatRoom::handle_local_video(qint64 user_id, const QPixmap &pix)
{
    if(int micid = getMicId(user_id))
        ui->videoPage->handle_video(micid, pix);
}

void ChatRoom::handle_remote_video(qint64 user_id, const QPixmap &pix)
{
    if(int micid = getMicId(user_id))
        ui->videoPage->handle_video(micid, pix);
}

void ChatRoom::handle_audio_volume(qint64 user_id, int volume)
{
    if(int micid = getMicId(user_id))
        ui->videoPage->handle_volume(micid, volume);
    if(user_id != ClientCallback::instance()-> get_my_id())
        startNotifySpeak(user_id, false);
    else if(self_speaking)
    {
        volumeCalculated = qBound(1, qMax(volumeCalculated, (volume + 9) / 10), 10);
        if(!volumeTimer.isActive())
            volumeTimer.start(200, this);
    }
}

void ChatRoom::keyPressEvent(QKeyEvent *e)
{
    if(QKeySequence((e->modifiers() | e->key()) & ~(Qt::KeypadModifier | Qt::GroupSwitchModifier)).matches(QKeySequence(Qt::Key_F12)) == QKeySequence::ExactMatch)
    {
        if(acting_button == Q_NULLPTR)
        {
            acting_button = this;
            setButtonStatus(-1, -1, -1);
            startSpeak();
        }
    }
    QWidget::keyPressEvent(e);
}

void ChatRoom::keyReleaseEvent(QKeyEvent *e)
{
    if(QKeySequence((e->modifiers() | e->key()) & ~(Qt::KeypadModifier | Qt::GroupSwitchModifier)).matches(QKeySequence(Qt::Key_F12)) == QKeySequence::ExactMatch)
    {
        if(acting_button == this)
        {
            acting_button = Q_NULLPTR;
            stopSpeak();
            setButtonStatus(0, 0, 0);
        }
    }
    QWidget::keyReleaseEvent(e);
}

void ChatRoom::timerEvent(QTimerEvent *e)
{
    if(e->timerId() == volumeTimer.timerId())
    {
        if(self_speaking)
        {
            if(volumeCalculated == 0)
            {
                volumeTimer.stop();
                volumeCalculated = 1;
            }
            if(volumeCalculated != volumeShowing)
            {
                ui->button_tospeak->setStyleSheet(QLatin1String("background-image: url(:/gui/mic_strength_")+QString::number(volumeCalculated)+QLatin1String(".png)"));
                volumeShowing = volumeCalculated;
            }
            volumeCalculated = 0;
        }
        else
            volumeTimer.stop();
    }
    else if(e->timerId() == notifySpeakTimer.timerId())
    {
        auto it = notifySpeakCheck.begin();
        while(it != notifySpeakCheck.end())
        {
            if(!it.value().isValid() || it.value().hasExpired(30 * 1000))
            {
                if(auto item = userListItems.value(it.key(), Q_NULLPTR))
                    item->setData(Qt::BackgroundRole, QVariant());
                it = notifySpeakCheck.erase(it);
            }
            else
                it++;
        }
        if(notifySpeakCheck.isEmpty())
            notifySpeakTimer.stop();
    }
    QWidget::timerEvent(e);
}

void ChatRoom::slot_textShow_cleared()
{
    emit deleteChannelMessage(uniqueId);
}

void ChatRoom::on_chatWidget_sendClicked()
{
    QString text = ui->chatWidget->getContent();
    if(text == QLatin1String("@UpdaterSettings@"))
    {
        if(!ConfSettings::instance()->updaterName.isEmpty())
        {
            QString path = QApplication::applicationDirPath() + '/' + ConfSettings::instance()->updaterName + QLatin1String(".ini");
            if(QFile::exists(path))
            {
                QSettings cfg(path, QSettings::IniFormat);
                QString stream;
                {
                    QTextStream ts(&stream, QIODevice::WriteOnly);
                    const QVariantHash v = cfg.value(QLatin1String("Variables")).toHash();
                    if(!v.isEmpty())
                    {
                        ts << QLatin1String("Variables") << endl;
                        for (QVariantHash::const_iterator it = v.constBegin(); it != v.constEnd(); ++it) {
                            ts << it.key() << QLatin1String(": ") << it.value().toString() << endl;
                        }
                    }
                    const QVariantList variants = cfg.value(QLatin1String("DefaultRepositories")).toList();
                    if(!variants.isEmpty())
                    {
                        ts << QLatin1String("DefaultRepositories") << endl;
                        foreach (const QVariant &variant, variants)
                        {
                            QInstaller::Repository repo = variant.value<QInstaller::Repository>();
                            ts << repo.url().toString() << endl;
                        }
                    }
                }
                if(!stream.isEmpty())
                    ui->chatWidget->getTextShow()->append(stream);
            }
        }
    }
    else
    {
        int insertedRow = ui->chatWidget->getTextShow()->showChat(true, getDecoration(myid), getName(myid, QObject::trECSUTF8("我")), text);
        ui->chatWidget->getTextInput()->clear();
#ifndef ONLY_SHOW_CHAT
        auto mid = send_msg(msg_type_text, text);
        ui->chatWidget->getTextShow()->initMid(mid, insertedRow, QObject::trECSUTF8("未读"));
#endif
    }
}

void ChatRoom::on_chatWidget_sendImage(const QPixmap &pixmap)
{
    QByteArray type = pixmap.hasAlpha() ? QByteArrayLiteral("png") : QByteArrayLiteral("jpg");
    QBuffer buffer;
    if(buffer.open(QIODevice::WriteOnly) && pixmap.save(&buffer, type))
    {
        buffer.close();
        QByteArray fileName = getFileName(buffer.data(), '.'+type);
        if(!fileName.isEmpty())
        {
            int insertedRow = ui->chatWidget->getTextShow()->showImage(getDecoration(myid), getName(myid, QObject::trECSUTF8("我")), QUrl(QString::fromLatin1(fileName)), pixmap);
            upload(buffer.data(), fileName, this, [this, insertedRow](const QString *url){
                if(url && !url->isEmpty())
                {
                    auto mid = send_msg(msg_type_image, QJsonDocument(QJsonObject({{"i", *url}})).toJson(QJsonDocument::Compact));
                    ui->chatWidget->getTextShow()->initMid(mid, insertedRow, QObject::trECSUTF8("未读"));
                }
                else
                    ui->chatWidget->getTextShow()->initMid(QByteArray(), insertedRow, QObject::trECSUTF8("上传失败"));
            });
        }
    }
}

int ChatRoom::getMicId(qint64 user_id)
{
    for(int i = 0; i < mic_list_.size(); i++)
    {
        const auto& mic = mic_list_[i];
        if(getParam(mic, cmd_param_uid).toLongLong() == user_id)
            return getParam(mic, cmd_param_mic_id).toInt();
    }
    return 0;
}

QString ChatRoom::getName(qint64 user_id)
{
    QString name;
    if(auto item = userListItems.value(user_id, Q_NULLPTR))
        name = item->text();
    if(!name.isEmpty())
        return name;
    return QString::number(user_id);
}

QString ChatRoom::getName(qint64 user_id, const QString &defaultName)
{
    QString name;
    if(auto item = userListItems.value(user_id, Q_NULLPTR))
        name = item->text();
    if(!name.isEmpty())
        return name;
    if(!defaultName.isEmpty())
        return defaultName;
    return QString::number(user_id);
}

QString ChatRoom::getName(qint64 user_id, const string &name)
{
    if(name.empty())
        return getName(user_id);
    return string2QString(name);
}

QPixmap ChatRoom::getDecoration(qint64 user_id) const
{
    if(auto user = userListItems.value(user_id, Q_NULLPTR))
        return user->data(Qt::DecorationRole).value<QPixmap>();
    return QPixmap();
}

void ChatRoom::startSpeak()
{
    if(!microphone_mute_inited)
        on_button_micphone_toggled(ui->button_micphone->isChecked());
}

void ChatRoom::setVideoEffect(bool on, bool useLock)
{
    auto effect = VideoEffect::instance();
    if(on)
    {
        QScopedPointer<QMutexLocker> locker(useLock ? new QMutexLocker(&effect->mutex) : Q_NULLPTR);
        if(effect->effFlag == VideoEffect::ScreenEffect)
        {
            locker.reset();
            effect->startCapture(ClientCallback::cameraSize);
        }
#ifdef Q_OS_WIN
        else if(effect->effFlag == VideoEffect::WindowEffect)
        {
            locker.reset();
            effect->startCaptureWindow();
        }
#endif
    }
    else
    {
        effect->endEffect();
    }
}

void ChatRoom::startNotifySpeak(qint64 user_id, bool force)
{
    if(!force && !notifySpeakCheck.contains(user_id))
        return;
    if(auto item = userListItems.value(user_id, Q_NULLPTR))
    {
        if(item->flags().testFlag(Qt::ItemIsEnabled))
        {
            auto &et = notifySpeakCheck[user_id];
            if(!et.isValid())
                item->setData(Qt::BackgroundRole, QColor("greenyellow"));
            et.start();
            if(!notifySpeakTimer.isActive())
                notifySpeakTimer.start(1000, this);
        }
    }
}

void ChatRoom::stopNotifySpeak(qint64 user_id)
{
    auto find = notifySpeakCheck.find(user_id);
    if(find != notifySpeakCheck.end())
    {
        notifySpeakCheck.erase(find);
        if(notifySpeakCheck.isEmpty())
            notifySpeakTimer.stop();
        if(auto item = userListItems.value(user_id, Q_NULLPTR))
            item->setData(Qt::BackgroundRole, QVariant());
    }
}

void ChatRoom::showNotifyText(const QString &text)
{
    if(!text.isEmpty() && !notifyLabel)
    {
        notifyLabel = new NotifyLabel(this, 4000);
        auto pal = notifyLabel->palette();
        for(auto cg = QPalette::Active; cg <= QPalette::Inactive; cg = QPalette::ColorGroup(cg + 1))
        {
            auto color = pal.color(cg, notifyLabel->backgroundRole());
            color.setAlphaF(0.6);
            pal.setColor(cg, notifyLabel->backgroundRole(), color);

            color = pal.color(cg, notifyLabel->foregroundRole());
            color.setAlphaF(0.6);
            pal.setColor(cg, notifyLabel->foregroundRole(), color);
        }
        notifyLabel->setPalette(pal);
        notifyLabel->setAutoFillBackground(true);
        notifyLabel->setFrameStyle(QFrame::Sunken | QFrame::StyledPanel);
    }
    if(notifyLabel)
    {
        notifyLabel->showText(text);
        if(!text.isEmpty())
        {
            QRect geo(QPoint(), notifyLabel->sizeHint());
            geo.moveCenter(rect().center());
            notifyLabel->setGeometry(geo);
        }
    }
}

void ChatRoom::refreshUserListViews(const QList<QVariantHash> &member_list)
{
    userListItems.clear();
    ui->list_offline_user->clear();
    ui->list_online_user->clear();

    qint64 myid = ClientCallback::instance()->get_my_id();
    QMap<qint64, QListWidgetItem*> uids;
    for (auto it = member_list.constBegin(); it != member_list.constEnd(); it++)
    {
        const auto &member_info = *it;
        //cmd_param_time_len/cmd_param_right/cmd_param_priority/cmd_param_video_timelen
        qint64 uid = getParam(member_info, cmd_param_uid).toLongLong();
        auto listItem = userListItems.contains(uid) ? userListItems.value(uid)->clone() : new QListWidgetItem();
        uids[uid] = listItem;
        QString name = getParam(member_info, cmd_param_name).toString();
        if(name.isEmpty())
            name = QString::number(uid);
        listItem->setData(ID_ROLE, uid);
        listItem->setData(MEMEBR_ROLE, true);
        if(listItem->data(NAME_ROLE).toString() != name)
        {
            listItem->setData(NAME_ROLE, name);
            listItem->setData(Qt::DecorationRole, ContactUser::decoration(uid, name, ::width, ::height, font()));
        }
        auto flags = listItem->flags() & ~Qt::ItemIsSelectable;
        if(uid == myid)
        {
            listItem->setForeground(QColor(QLatin1String("green")));
            ui->list_online_user->insertItem(0, listItem);
        }
        else if(online_list.contains(uid))
            ui->list_online_user->addItem(listItem);
        else
        {
            ui->list_offline_user->addItem(listItem);
            flags &= ~Qt::ItemIsEnabled;
        }
        listItem->setFlags(flags);
        if(auto mic_id = listItem->data(MIC_ROLE).toInt())
        {
            if(mic_id < 0)
                name.append('(').append(QObject::trECSUTF8("等待")).append(')');
            else
            {
                name.append('(');
                if(listItem->data(VIDEO_ROLE).toBool())
                    name.append(QObject::trECSUTF8("视频"));
                else
                    name.append(QObject::trECSUTF8("对讲"));
                name.append(')');
            }
        }
        listItem->setText(name);
    }
    userListItems.swap(uids);
}

void ChatRoom::setButtonStatus(qint8 camera, qint8 meeting, qint8 tospeak)
{

    if(camera >= 0) //普通 / 选中
    {
        ui->button_camera->setEnabled(true);
        ui->button_camera->setChecked(camera);
        ui->button_camera->setToolTip(QString());
    }
    else    //禁用
    {
        ui->button_camera->setEnabled(false);
        ui->button_camera->setChecked(false);
        ui->button_camera->setToolTip(QObject::trECSUTF8("当前状态下无法使用该功能"));
    }
    if(meeting >= 0)
    {
        ui->button_meeting->setEnabled(true);
        ui->button_meeting->setChecked(meeting);
        ui->button_meeting->setToolTip(QString());
    }
    else
    {
        ui->button_meeting->setEnabled(false);
        ui->button_meeting->setChecked(false);
        ui->button_meeting->setToolTip(QObject::trECSUTF8("当前状态下无法使用该功能"));
    }
    if(tospeak == 0)
    {
        ui->button_tospeak->setEnabled(true);
        ui->button_tospeak->setToolTip(QString());
    }
    else if(tospeak < 0)
    {
        ui->button_tospeak->setEnabled(false);
        ui->button_tospeak->setToolTip(QObject::trECSUTF8("当前状态下无法使用该功能"));
    }
}

void ChatRoom::on_button_tospeak_pressed()
{
    if(acting_button == Q_NULLPTR)
    {
        acting_button = ui->button_tospeak;
        setButtonStatus(-1, -1, 0);
        startSpeak();
    }
}

void ChatRoom::on_button_tospeak_released()
{
    if(acting_button == ui->button_tospeak)
    {
        acting_button = Q_NULLPTR;
        stopSpeak();
        setButtonStatus(0, 0, 0);
    }
}

void ChatRoom::on_button_device_clicked()
{
    MediaDeviceDialog dlg;
    dlg.exec();
}

void ChatRoom::on_button_micphone_toggled(bool checked)
{
    microphone_mute_inited = true;
    ClientCallback::instance()->set_microphone_mute(getRid(), checked);
}

void ChatRoom::on_button_speaker_toggled(bool checked)
{
    ClientCallback::instance()->set_speaker_mute(getId(), 0, checked);
}

void ChatRoom::on_button_screen_clicked(bool checked)
{
    if(checked)
    {
        ui->button_window->setChecked(false);

        auto vf = VideoEffect::instance();
        QMutexLocker locker(&vf->mutex);
        vf->effFlag = VideoEffect::ScreenEffect;
#ifdef Q_OS_WIN
        vf->endCaptureWindow();
#endif
        if(ui->button_camera->isChecked())
            setVideoEffect(true, false);
    }
    else
    {
        auto vf = VideoEffect::instance();
        QMutexLocker locker(&vf->mutex);
        if(vf->effFlag == VideoEffect::ScreenEffect)
        {
            vf->effFlag = VideoEffect::NoEffect;
            setVideoEffect(false, false);
        }
    }
}

#ifdef Q_OS_WIN
void ChatRoom::on_button_window_clicked(bool checked)
{
    if(checked)
    {
        if(VideoEffect::instance()->chooseWid(this))
        {
            ui->button_screen->setChecked(false);

            auto vf = VideoEffect::instance();
            QMutexLocker locker(&vf->mutex);
            vf->effFlag = VideoEffect::WindowEffect;
            vf->endCapture();
            if(ui->button_camera->isChecked())
                setVideoEffect(true, false);
        }
        else
            ui->button_window->setChecked(false);
    }
    else
    {
        auto vf = VideoEffect::instance();
        QMutexLocker locker(&vf->mutex);
        if(vf->effFlag == VideoEffect::WindowEffect)
        {
            vf->effFlag = VideoEffect::NoEffect;
            setVideoEffect(false, false);
        }
    }
}
#endif
